package com.ms.p2p.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.ms.p2p.Constants;
import com.ms.p2p.bean.Captcha;
import com.ms.p2p.controller.BaseController;

import com.ms.p2p.service.RSAService;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.interfaces.RSAPublicKey;
import java.util.Random;


@Controller
@RequestMapping("/common")
public class CommonController extends BaseController {

    @Autowired
    private RSAService rsaService;

    @RequestMapping("/error")
    public String error(HttpServletResponse response, HttpSession session) {
        return "html/500";
    }

    @RequestMapping("/resource_not_found")
    public String resource_not_found(HttpServletResponse response,
                                     HttpSession session) {
        return "html/404";
    }


    @RequestMapping("/tips")
    public String tips(HttpServletRequest request, HttpSession session) {
        return "customer/msgTips";
    }

    /**
     * 获取加密公钥
     */
    @RequestMapping(value = "/key")
    @ResponseBody
    public JSONObject publicKey(HttpServletRequest request) {
        RSAPublicKey rsapublickey = rsaService.generateKey(request);

        JSONObject obj = new JSONObject();
        obj.put("modulus", Base64.encodeBase64String(rsapublickey.getModulus().toByteArray()));
        obj.put("exponent", Base64.encodeBase64String(rsapublickey.getPublicExponent().toByteArray()));
        return obj;
    }

    @RequestMapping("/random")
    public void random(HttpServletResponse response, HttpSession session)
            throws IOException {
        Captcha code = new Captcha();
        session.setAttribute(Constants.CAPTCHA_SESSION_KEY, code.getCode());
//        String code1 = (String) session.getAttribute(Constants.CAPTCHA_SESSION_KEY);
        OutputStream output = response.getOutputStream();
        ImageIO.write(code.getBuffImg(), "JPEG", output);
        output.flush();

    }


    private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色
        Random random = new Random();
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

}
